let http = require('http');
let fs = require('fs');
let path = require('path');

let options = {
    hostname: 'localhost',
    port: 8080,
    path: '/',
    method: 'GET'
}

let ws = fs.createWriteStream('./download.png');
let pause = false;
let start = 0;
let speed = 100000;
let end = start + speed;

download();
process.stdin.on('data', function (chunk) {
    chunk = chunk.slice(0, chunk.length - 2);
    option = chunk.toString();
    console.log(option)
    switch (option) {
        case 'p':
            pause = true;
            break;
        case 'c':
            pause = false;
            download();
        default:
            if (/^s\s-[0-9]+$/.test(option)) {
                option = option.slice(3);
                speed = parseInt(option);
            }

    }
});

//--- --- ---
function download() {
    options.headers = {
        Range: `bytes=${start}-${end}` //请求头看这里
    }
    http.get(options, function (res) {
        let range = res.headers['content-range'];
        let total = parseInt(range.split('/')[1]);
        console.log(total);
        let buffers = [];
        let nextEnd;
        res.on('data', function (chunk) {
            buffers.push(chunk);
        });
        res.on('end', function () {
            ws.write(Buffer.concat(buffers));
            setTimeout(function () {
                start = end + 1;
                nextEnd = end + speed;
                end = (nextEnd + 1) < total ? nextEnd : total;
                if (pause === false && start < total) {
                    download();
                }
            }, 100)
        })
    })
}
